﻿using Dapper;
using ML.Entity;
using ML.IRepository;
using System.Linq;
using System.Collections.Generic;

namespace ML.Repository
{
    /// <summary>
    /// 产品仓储实现类
    /// </summary>
    public class ProductRepository : DBFactory, IProductRepository
    {
        public Pager<ProductResponse> List(ProductSearch productSearch)
        {
            //组装调用存储过程参数
            var criteria = new PageCriteria() { TableName = "ml_product p INNER JOIN ml_productcategory pc on p.CategoryId = pc.Id INNER JOIN ml_merchant m on p.MerchantId = m.Id" };
            if (!string.IsNullOrEmpty(productSearch.merchantid_search))
            {
                criteria.Conditions += string.Format(" AND m.Id='{0}'", productSearch.merchantid_search);
            }
            if (!string.IsNullOrEmpty(productSearch.merchantname_search))
            {
                criteria.Conditions += string.Format(" AND m.Name LIKE '%{0}%'", productSearch.merchantname_search);
            }
            if (!string.IsNullOrEmpty(productSearch.name_search))
            {
                criteria.Conditions += string.Format(" AND p.Name LIKE '%{0}%'", productSearch.name_search);
            }
            if (productSearch.ualmark_search != -1)
            {
                criteria.Conditions += string.Format(" AND p.UALMark={0}", productSearch.ualmark_search);
            }
            criteria.Conditions += string.Format(" AND p.DelMark=0");

            criteria.PageIndex = productSearch.pageindex;
            criteria.Field = @"pc.Name ProductCategoryName,m.Name MerchantName,p.*";
            criteria.PageSize = productSearch.pagesize;
            criteria.SortName = productSearch.ordername;
            if (productSearch.orderby)
            {
                criteria.Sort = "DESC";
            }
            else
            {
                criteria.Sort = "ASC";
            }

            //调用存储过程进行查询并且返回
            var list = GetPageData<ProductResponse>(criteria);
            return list;
        }

        public ProductEntity GetById(string id)
        {
            throw new System.NotImplementedException();
        }

        public ProductResponse GetDetailById(string id)
        {
            const string sql = @"SELECT pc.Name ProductCategoryName,m.Name MerchantName,p.* FROM ml_product p 
	                INNER JOIN ml_productcategory pc on p.CategoryId=pc.Id
	                INNER JOIN ml_merchant m on p.MerchantId=m.Id
                WHERE p.Id=@Id";
            using (_db)
            {
                return _db.Query<ProductResponse>(sql, new { @Id = id }).FirstOrDefault();
            }
        }

        public IEnumerable<ProductResponse> GetListByMerchantId(string id, int pageindex, int pagesize)
        {
            const string sql = @"SELECT pc.Name ProductCategoryName,p.* FROM ml_product p 
	                INNER JOIN ml_productcategory pc on p.CategoryId=pc.Id 
                    WHERE p.MerchantId=@MerchantId AND p.DelMark=0 Limit @Start,@End";
            using (_db)
            {
                return _db.Query<ProductResponse>(sql, new { @MerchantId = id, @Start = (pageindex - 1) * pagesize, @End = pagesize });
            }
        }

        public IEnumerable<ProductEntity> GetProductInfoList()
        {
            const string sql = @"SELECT * FROM ml_product WHERE UALMark=1 AND DelMark=0";
            using (_db)
            {
                return _db.Query<ProductEntity>(sql);
            }
        }

        public decimal GetDiscountPriceByProductId(string productId)
        {
            const string sql = @"SELECT DiscountPrice FROM ml_product WHERE Id=@Id";
            using (_db)
            {
                return _db.Query<decimal>(sql, new { @Id = productId }).FirstOrDefault();
            }
        }

        public IEnumerable<ProductEntity> GetListByCategoryId(string id)
        {
            const string sql = @"SELECT * FROM ML_Product WHERE CategoryId=@CategoryId";
            using (_db)
            {
                return _db.Query<ProductEntity>(sql, new { @CategoryId = id });
            }
        }

        public bool Add(ProductEntity entity)
        {
            const string sql = @"INSERT INTO ml_product(Id,CategoryId,MerchantId,Name,PreviewImg,OriginalPrice,DiscountPrice,
                    Description,SalesVolume,PraiseRate,Tag,Type,IsLimitPurchase,LimitPurchaseCopies,UALMark,DelMark,CreateTime) 
                VALUES(@Id,@CategoryId,@MerchantId,@Name,@PreviewImg,@OriginalPrice,@DiscountPrice,@Description,@SalesVolume,
                    @PraiseRate,@Tag,@Type,@IsLimitPurchase,@LimitPurchaseCopies,@UALMark,@DelMark,@CreateTime)";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Update(ProductEntity entity)
        {
            const string sql = @"UPDATE ml_product SET CategoryId=@CategoryId,Name=@Name,PreviewImg=@PreviewImg,
                OriginalPrice=@OriginalPrice,DiscountPrice=@DiscountPrice,Description=@Description,Tag=@Tag,Type=@Type,
                IsLimitPurchase=@IsLimitPurchase,LimitPurchaseCopies=@LimitPurchaseCopies WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool UpdateSalesVolume(string id, int count)
        {
            const string sql = @"UPDATE ml_product SET SalesVolume=@SalesVolume WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, new { @SalesVolume = count, @Id = id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool UalMark(string id, int ualmark)
        {
            const string sql = @"UPDATE ml_product SET UALMark=@UALMark WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, new { @UALMark = ualmark, @Id = id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Delete(ProductEntity entity)
        {
            throw new System.NotImplementedException();
        }

        public bool Delete(string id)
        {
            const string sql = @"UPDATE ml_product SET DelMark=1 WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, new { @Id = id }) > 0)
                {
                    return true;
                }
                return false;
            }
        }
    }
}